package com.example.financeapi.config.interceptor;


import com.example.financeapi.entity.vo.ResultException;
import com.example.financeapi.entity.vo.ResultVOUtil;
import com.example.financeapi.entity.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

/**
 * 异常处理拦截器
 * @author Alvin
 */
@Slf4j
@CrossOrigin
@ControllerAdvice
@RestControllerAdvice
public class FinanceExceptionHandler {

    /**
     * 通用异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResultVo handleException(Exception e){
        log.error("异常处理拦截器 -->"+e.getMessage(), e);
        return ResultVOUtil.error(e.getMessage(), e);
    }

    /**
     * 自定义异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = ResultException.class)
    public ResultVo handlerException(ResultException e) {
        return ResultVOUtil.error(e.getCode(), e.getMessage());
    }

    /**
     * 类型错误
     * @param ex
     * @return
     */
    @ExceptionHandler({TypeMismatchException.class})
    public ResultVo requestTypeMismatch(TypeMismatchException ex) {
        return ResultVOUtil.error(ex.getErrorCode(), ex.getMessage());
    }

    /**
     * 数据库异常
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultVo handleDuplicateKeyException(DuplicateKeyException e){
        log.error("异常处理拦截器 -->"+e.getMessage(), e);
        return ResultVOUtil.error("数据库中已存在该记录");
    }

}